const http = require("http");
const https = require("https");
const Koa = require("koa");

const bodyParser = require("koa-bodyparser");

const static = require("koa-static");

const cors = require("koa-cors");

const config = require("./app.config");

const router = require("./app.router")();

const contextExtend = require("./extend/context");

const errorHandle = require("./middlewares/errorHandle");

const app = new Koa();

// 拓展context
contextExtend(app);

//错误处理
app.use(errorHandle());

//解决跨域问题
app.use(cors());

// 解析post请求的请求体
app.use(bodyParser());

// 配置静态资源文件路径
app.use(static(config.staticDir));

// 不同请求方法的参数配置
app.use(async function(ctx, next) {
  let method = ctx.method.toUpperCase();
  if (method === "GET" || method === "DELETE") {
    ctx.params = ctx.query;
  } else if (method === "POST" || method === "PUT") {
    ctx.params = ctx.request.body;
  }
  await next();
});

// 路由中间件
app.use(router.routes(), router.allowedMethods());

// 监听端口
// app.listen(config.port);

const serverType = config.server.type;

if (serverType.includes("http") && serverType.includes("https")) {
  http.createServer(app.callback()).listen(config.httpPort);
  https.createServer(app.callback()).listen(config.httpsPort);
  console.log("双服务器类型启动成功");
} else if (serverType.includes("http")) {
  http.createServer(app.callback()).listen(config.httpPort);
  console.log("potr:" + config.httpPort, "http服务器启动成功");
} else if (serverType.includes("https")) {
  https.createServer(app.callback()).listen(config.httpPort);
  console.log("potr:" + config.httpPort, "https服务器启动成功");
}
